package com.order.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.entity.Order;
import com.common.entity.OrderShop;
import com.common.entity.Shopcar;
import com.common.entity.Shop;
import com.common.untils.CommonResult;
import com.github.wxpay.sdk.WXPayUtil;

import com.order.mapper.OrderMapper;
import com.order.service.IOrderService;
import com.order.untils.HttpClient;
import com.order.vo.OrderGenerationVO;
import com.order.vo.OrderVo;
import com.sun.org.apache.xpath.internal.operations.Or;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xdl
 * @since 2022-08-31
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    @Resource
    private OrderMapper orderMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;


    @Value("${weixin.appid}")
    private String appId;
    @Value("${weixin.mch_id}")
    private String mchId;
    @Value("${weixin.api_key}")
    private String apikey;

    @Override
    public CommonResult findAllOrder( OrderVo orderVo) {
        Page<Map> page = new Page<>(orderVo.getCurrentPage(),orderVo.getPageSize());
        QueryWrapper<Map> objectQueryWrapper = new QueryWrapper<>();
        if(StringUtils.hasText(orderVo.getName())){
            objectQueryWrapper.like("name",orderVo.getName());
        }
        if(StringUtils.hasText(orderVo.getOrderData())){
            objectQueryWrapper.like("order_date",orderVo.getOrderData());
        }
        if(StringUtils.hasText(orderVo.getSoid())){
            objectQueryWrapper.eq("soid",orderVo.getSoid());
        }
        objectQueryWrapper.eq("s.is_deleted",0);
        IPage<Map> allOrder = orderMapper.findAllOrder(page,objectQueryWrapper);
        return new CommonResult(2000,"查询成功",allOrder);
    }

    @Override
    public CommonResult orderGeneration(OrderGenerationVO orderGenerationVO,String homeToken) {
        //时间戳+随机数
        Random r = new Random();
        int i = r.nextInt(900000)+100000;
        long a = new Date().getTime();
        String shijian =String.valueOf(a) +String.valueOf(i);

        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(currentTime);

        //token获取当前登录着id
        ValueOperations<String, String> forValue = redisTemplate.opsForValue();
        String s = forValue.get(homeToken);
        Map map = JSON.parseObject(s, Map.class);
        JSONObject client = (JSONObject) map.get("client");
        String bid = client.getString("id");


        Order order = new Order();
        order.setUid(bid);
        order.setShopId(orderGenerationVO.getShopId());
        order.setOrderDate(dateString);
        order.setOrderPay(orderGenerationVO.getOrderPay());
        order.setSoid(shijian);
        order.setState(1);

        OrderShop orderShop = new OrderShop();
        orderShop.setGid(orderGenerationVO.getId());//商品id
        orderShop.setGoodsname(orderGenerationVO.getGoodsname());//商品名
        orderShop.setImg(orderGenerationVO.getImg());//商品图片
        orderShop.setTypename(orderGenerationVO.getTypename());//商品类型
        orderShop.setGsname(orderGenerationVO.getGsname());//商品规格
        orderShop.setGbname(orderGenerationVO.getGbname());//商品品牌
        orderShop.setGdname(orderGenerationVO.getGdname());//商品储藏
        orderShop.setDprice(orderGenerationVO.getDprice());//商品单价
        orderShop.setZprice(orderGenerationVO.getZprice());//商品总价
        orderShop.setTbQuantity(orderGenerationVO.getTbQuantity());//商品数量
        orderShop.setSname(orderGenerationVO.getSname());//店铺名称
        System.out.println(orderGenerationVO.getId()+"1111111111111111111111111111111111111111");
        System.out.println(orderGenerationVO.getGid()+"2222222222222222222222222222222222222222222222222222");
        int insert = baseMapper.insert(order);
        orderShop.setOid(order.getId());
        int insert01 = orderMapper.insertShop(orderShop);

        if (insert!=0&&insert01!=0){
            return new CommonResult(2000,"添加成功",shijian);
        }
        return new CommonResult(5000,"添加失败",null);
    }

    //微信支付
    //根据订单号创建二维码
    @Override
    public CommonResult createNative(String orderNo) {
        //1.根据订单号查询出订单信息
        QueryWrapper wrapper=new QueryWrapper();
        //前端传过来的订单号跟数据库中的订单号一致
        wrapper.eq("soid",orderNo);
        //订单状态为1
        wrapper.eq("state",1);
        List<Order> list = orderMapper.selectList(wrapper);
        for (Order order:list) {
            if (order != null) {
                try {
                    //接口里面的参数要的是xml类型
                    //设置请求的参数个数格式为xml格式
                    //将请求参数封装成map
                    Map<String, String> params = new HashMap<>();
                    //添加公众账号Id
                    params.put("appid", appId);
                    //添加商品号
                    params.put("mch_id", mchId);
                    //添加随机字符串--微信自带算法
                    params.put("nonce_str", WXPayUtil.generateNonceStr());
                    //添加商品描述
                    params.put("body", order.getOrderDate());
                    //添加商品订单号
                    params.put("out_trade_no", orderNo);
                    //添加标价金额 --单位是分，要转换
                    params.put("total_fee", new BigDecimal(0.01).multiply(new BigDecimal(100)).longValue() + "");
                    //添加终端ip
                    params.put("spbill_create_ip", "127.0.0.1");
                    //添加通知地址
                    params.put("notify_url", "http://localhost:8888/pay/back");
                    //添加交易类型
                    params.put("trade_type", "NATIVE");

                    //创建HttpClient对象--作用远程调用
                    HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
                    //支持https协议
                    client.setHttps(true);
                    //将map转为xml格式--设置请求的参数
                    client.setXmlParam(WXPayUtil.generateSignedXml(params,apikey));
                    //发送请求
                    client.post();
                    //获取请求响应响应的结果
                    String content = client.getContent();
                    //将String类型转换为map返货给前端
                    Map<String, String> map = WXPayUtil.xmlToMap(content);
                    if (map.get("result_code").equals("SUCCESS")){
                        Map<String,Object> result=new HashMap<>();
                        result.put("codeUrl",map.get("code_url"));
                        result.put("price",order.getOrderPay());
                        result.put("orderNo",orderNo);
                        return new CommonResult(2000,"生成二维码",result);
                    }

                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }

        //判断订单信息不为空

        return new CommonResult(5000,"订单失效",null);
    }
    //根据订单状态查询微信支付情况
    @Override
    public CommonResult queryPayStatus(String orderNo) {
        //1.根据订单状态查询微信支付情况
        try {
            HttpClient client=new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            //设置参数--分装成map在转为xml格式
            Map<String, String> params = new HashMap<>();
            //添加公众账号Id
            params.put("appid", appId);
            //添加商品号
            params.put("mch_id", mchId);
            //添加商品订单号
            params.put("out_trade_no",orderNo);
            //添加随机字符串
            params.put("nonce_str",WXPayUtil.generateNonceStr());
            //支持Https
            client.setHttps(true);
            client.setXmlParam(WXPayUtil.generateSignedXml(params,apikey));
            client.post();
            String content = client.getContent();
           /* System.out.println(content);*/
            //转换为map
            Map<String, String> map = WXPayUtil.xmlToMap(content);
            if (map.get("trade_state").equals("SUCCESS")){
                QueryWrapper<Order> wrapper=new QueryWrapper<>();
                //根据订单号
                wrapper.eq("soid",orderNo);
                wrapper.eq("state",1);
                List<Order> orders = orderMapper.selectList(wrapper);
                for (Order o : orders) {
                    List<Map> maps =   orderMapper.selectShopOrder(o.getId());
                    for (Map m : maps) {
                        orderMapper.updataShopGoods(o.getShopId(),m.get("gid"),Integer.parseInt(m.get("tb_quantity").toString()));
                    }
                }
                //1.修改订单的状态
                Order order=new Order();
                order.setState(0);
                order.setGmtModified(LocalDateTime.now());
                order.setPayType(0);
                orderMapper.update(order,wrapper);

                //查询商品购买数量
                return new CommonResult(2000,"支付成功",null);
            }

        }catch (Exception e){
            e.printStackTrace();
        }

        return new CommonResult(5000,"支付失败",null);
    }

    //取消支付
    @Override
    public CommonResult cancelPayment(Integer id){
        int i = orderMapper.deleteById(id);
        if (i!=0){
            return new CommonResult(2000,"删除成功(逻辑)",null);
        }
         return new CommonResult(2000,"删除失败(逻辑)",null);
    }

    //购物车购买
    @Override
    public CommonResult orderGeneration1(Integer zongjia, List<Map> maps, String homeToken) {
        //时间戳+随机数
        Random r = new Random();
        int i = r.nextInt(900000)+100000;
        long a = new Date().getTime();
        String shijian =String.valueOf(a) +String.valueOf(i);

        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(currentTime);

        //token获取当前登录着id
        ValueOperations<String, String> forValue = redisTemplate.opsForValue();
        String s = forValue.get(homeToken);
        Map map = JSON.parseObject(s, Map.class);
        JSONObject client = (JSONObject) map.get("client");
        String bid = client.getString("id");

       /* //order++++++++++
        Order order = new Order();
        order.setUid(bid);
        order.setOrderDate(dateString);
        order.setOrderPay(zongjia.doubleValue());
        order.setSoid(shijian);
        order.setState(1);
        int insert = baseMapper.insert(order);*/

        for (Map m : maps) {
            //order++++++++++
            Order order = new Order();
            order.setUid(bid);
            int gsid = Integer.parseInt(m.get("gsid").toString());
            order.setShopId(gsid);
            order.setOrderDate(dateString);
            order.setOrderPay(zongjia.doubleValue());
            order.setSoid(shijian);
            order.setState(1);
            //orderShop+++++++
            OrderShop orderShop = new OrderShop();
            orderShop.setGid(m.get("gid").toString());//商品id
            orderShop.setGoodsname(m.get("gname").toString());//商品名
            orderShop.setImg((m.get("img").toString()));//商品图片
            orderShop.setTypename(m.get("typename").toString());//商品类型
            orderShop.setGsname((m.get("gsname").toString()));//商品规格
            orderShop.setGbname((m.get("gbname").toString()));//商品品牌
            orderShop.setGdname((m.get("gdname").toString()));//商品储藏
            orderShop.setDprice(m.get("sellingprice").toString());//商品单价
            double sellingprice = Double.parseDouble(m.get("sellingprice").toString());
            int counts = Integer.parseInt(m.get("gscounts").toString());
            Double zongjiage=sellingprice*counts;
            orderShop.setZprice(zongjiage.toString());//商品总价
            orderShop.setTbQuantity(counts);//商品数量
            orderShop.setSname(m.get("name").toString());//店铺名称

            int insert = baseMapper.insert(order);
            orderShop.setOid(order.getId());
            int insert01 = orderMapper.insertShop(orderShop);
            //查询购物车订单
            Integer id = (Integer) m.get("id");
            QueryWrapper<Shopcar> objectQueryWrapper = new QueryWrapper<>();
            objectQueryWrapper.eq("id",m.get("id"));
            if (insert!=0){
                Shopcar shopcar = new Shopcar();
                shopcar.setIsDeleted(1);
                shopcar.setId(id);
                orderMapper.updateShopCar(shopcar);
            }
        }
            return new CommonResult(2000,"添加成功",shijian);

    }

    @Override
    public CommonResult getOrderCharts() {
        List<Shop> shopList = orderMapper.getShop();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("state",0);
        List<Order> list = orderMapper.selectList(queryWrapper);
        Double sum = 0.00;
        List<Map> map = new ArrayList<>();
        for (Shop s : shopList) {
            for (Order o: list) {
                if (s.getId()==o.getShopId()){
                    sum = sum+o.getOrderPay();
                }
            }
            Map map1 = new HashMap();
            map1.put("name",s.getName());
            map1.put("value",sum);
            map.add(map1);
            sum=0.0;

        }
        return  new CommonResult(2000,"查询成功",map);
    }


}
